<?php
declare (strict_types = 1);

namespace app\admin\controller;

use think\Request;
use app\admin\middleware\Auth;
use think\facade\View;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\facade\Db;

class Common
{
	public $model; # 当前模型
	public $validate; # 当前验证器
	public $title; # 当前标题
	public $searchField; # 允许搜索的字段
	public $tables;

	/**
	 * 权限验证
	 */
	protected $middleware = [
		//Auth::class
		Auth::class=>['except'=>['upload']],
	];

	/**
	 * 构造方法
	 */
	public function __construct(){
		/**
		 * 用户信息
		 */
		$administrator = session('administrator');
		View::assign('admin',$administrator);

		/**
		 * 左侧菜单
		 */
		$menumodel = new \app\admin\model\Menu();
		$list = $menumodel->left();
		View::assign('lefts',$list);

		/**
		 * 当前路径
		 */
		$controller =  request()->controller();
		$action =  request()->action();
		$root = request()->root();
		$pathinfo = "{$controller}/$action";
		View::assign('now_route',[
			'controller'=>$controller,
			'action'=>$action,
			'root'=>$root,
			'url'=>$pathinfo
		]);

		/**
		 * 当前get参数
		 */
		$getparam = request()->param();
		$getparam['action'] = "excel";
		View::assign('getparam',$getparam);
		
		/**
		 * 域名
		 */
		$this->domain = "http://".$_SERVER["SERVER_NAME"];
		#$this->domain = config('web.domain');	
		
	}

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
		$where = $this->search();
		$order = $this->order();
		$lists = $this->model->getpage($where,$order);
		$data['lists'] = $lists;
		return view('index',$data);
    }

	/**
	 * where
	 */
	protected function search(){
		$get_data = request()->param();
		$where = [];
		if(!empty($get_data)){
			foreach($get_data as $key=>$value){
				if(!empty($this->searchField)){
					if(in_array($key,$this->searchField)){
						if(!empty($value)){
							$where[] = [$key,'like','%'.$value.'%']; 
						}
					}
				} else {
					if(!empty($this->tables['fields'][$key])){
						if(!empty($value)){
							$where[] = [$key,'like','%'.$value.'%']; 
						}
					}
				}
			}
		}
		return $where;
	}

	/**
	 * order
	 */
	protected function order(){
		return 'id desc';
	}

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create(Request $request)
    {
		$re = $this->update($request);
		if(!empty($re)){
			return $re;
		}
		return view('create');
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read(Request $request)
    {
		$id = intval(input('param.id'));
		$info = $this->model->find($id);
		return view('read',[
			'info'=>$info
		]);	
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit(Request $request)
    {
		$re = $this->update($request);
		if(!empty($re)){
		return $re;
		}

		$id = intval(input('param.id'));
		$info = $this->model->find($id);
		return view('edit',[
		'info'=>$info
		]);	
    }

	/**
	 * 复制
	 */
    public function copy(Request $request)
    {
		$id = intval(input('param.id'));
		$info = $this->model->find($id);
		if($info){
			$data = $info->getData();
			unset($data['id']);
			$re = $this->model->insert($data);
			if($re){
				return json([
					'status'=>1,
					'notice'=>'复制成功！'
				]);
			} else {
				return json([
					'status'=>2,
					'notice'=>'复制成功！'
				]);
			}
		} else {
			return json([
				'status'=>2,
				'notice'=>'活动不存在！'
			]);
		}
    }


	/**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    protected function update(Request $request,$validate = "",$savedata = "savedata")
    {
		if('POST' == $request->method()){
			$data = $request->param();

			if(empty($validate)){
				$validate = $this->validate;
			}
			$result = $validate->check($data);
			if(!$result){
				return json([
					'status'=>2,
					'notice'=>$validate->getError(),
				]);
			} else {
				$revalue = $this->model->$savedata($data);
				if(1 == $revalue['status']){ 
					return json($revalue);
				} else { # 登录失败
					return json($revalue);
				}
			}
		} else {
			return null;
		}
    }

	/**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete(Request $request)
    {
		$id = $request->param('id');
		if(is_array($id) && !empty($id)){
			$idarr = $id;
		} else {
			if(!empty($id)){
				$idarr = explode(',',$id);
			} else {
				return json([
					'status'=>2,
					'notice'=>"请选择要删的条目！",
				]);
			}
		}
		if(!empty($idarr)){
			$msg = $this->model->destroy($idarr);
			if($msg){
				return json([
					'status'=>1,
					'notice'=>"删除成功！",
				]);
			} else {
				return json([
					'status'=>2,
					'notice'=>"删除失败！",
				]);
			}
		} else {
			return json([
				'status'=>2,
				'notice'=>"ID 不能为空！",
			]);
		}
    }
	
	/**
	 * 空操作
	 */
	public function __call($method, $args){
		return view('layout/error',[
			'error' =>'操作不存在！'
		]);
	}

	/**
	 * 导出Excel表格 Xlsx格式(2007版)
	 *
	 * @author liang <23426945@qq.com>
	 * @datetime 2019-12-22
	 * 
	 * @param  array  $title    表头单元格内容
	 * @param  array  $data     从第二行开始写入的数据
	 * @param  string $path 	Excel文件保存位置,路径中的目录必须存在
	 *
	 * @return null 没有设定返回值
	 */
	protected function getExcel($title = [], $data = [], $path = '')
	{
		// 获取Spreadsheet对象
		$spreadsheet = new Spreadsheet();
		$sheet = $spreadsheet->getActiveSheet();

		// 表头单元格内容 第一行
		$titCol = 'A';
		foreach ($title as $value) {
			// 单元格内容写入
			$sheet->setCellValue($titCol . '1', $value);
			$sheet->getColumnDimension($titCol)->setAutoSize(true);
			$titCol++;
		}	


		// 从第二行开始写入数据
		$row = 2;
		foreach ($data as $item) {
			$dataCol = 'A';
			foreach ($item as $value) {
				// 单元格内容写入
				$sheet->setCellValue($dataCol . $row, $value." ");
				$sheet->getStyle($dataCol . $row)->getAlignment()->setWrapText(true);
				$dataCol++;
			}
			$row++;
		}
	 
		$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');

		$result = $writer->save($path . '.xlsx');
	}

	/**
	 * 导出excel
	 */
	public function excel(){
		$excel = request()->param('action');
		if(!empty($excel) && $excel == 'excel'){
			$where = $this->search(request());
			$order = $this->order(request());
			$lists = $this->model->getall($where,$order);
			$name = date('Y-m-d').time();
			$filename = '../excel/'.$name;
			$fields = $this->tables['fields'];
			$fields_name = [];
			foreach($fields as $key=>$value){
				$fields_name[] = $value['name'];
			}
			$this->getExcel($fields_name, $lists, $filename);
			return download($filename.".xlsx", $filename.".xlsx");
		}
	}

	/**
	 * 上传
	 */
	public function upload(){
		$files = request()->file();
		try {
			validate(['image'=>'filesize:10240|fileExt:jpg,png,jpeg,gif'])
				->check($files);
			$savenames = [];
			foreach($files as $file) {
				$savenames[] = \think\facade\Filesystem::disk('public')->putFile( 'zscuploads', $file);
			}
			$strsavename = implode('|',$savenames);
			return json([
				'status'=>1,
				'files'=>$this->domain."/storage/".$strsavename
			]);
		} catch (\think\exception\ValidateException $e) {
			return json([
				'status'=>2,
				//'notice'=>$e->getMessage(),
				'notice'=>'上传失败！'
			]);
		}
	}
	
	/**
	 * 代码工具
	 */
	public function codetools(){
		$read = $this->getread();
		View::assign('read',$read);

		$create = $this->getcreate();
		View::assign('create',$create);

		$edit = $this->getedit();
		View::assign('edit',$edit);

		$list = $this->getlist();
		View::assign('list',$list);
		View::assign('title',"LIST");

		if(!empty($this->auth_rule)){
			foreach($this->auth_rule as $key=>$value){
				$info = Db::name('auth_rule')
					->where('name',$value['name'])
					->find();
				if(empty($info)){
					$value['create_time'] = time();
					$value['update_time'] = time();
					Db::name('auth_rule')->insert($value);
				}
			}
		}

		return view('layout/code');
	}
	
	/**
	 * 获取 read 模板代码
	 */
	protected function getread(){
		$div = "";
		foreach($this->tables['fields'] as $key=>$value){
			if(!empty($value['type'])) {
				switch($value['type']){
					case 'image':
						$div .= '
							<tr>
								<td>{$tables["fields"]["'.$key.'"]["name"]}</td>
								<td>
								{if !empty($info["'.$key.'"])}
									<img src="{$info["'.$key.'"]}" width="100">
								{/if}
								</td>
							</tr>
						';
					break;
					case 'ueditor':
						$div .= '
							<tr>
								<td>{$tables["fields"]["'.$key.'"]["name"]}</td>
								<td>
									{:htmlspecialchars_decode($info["'.$key.'"])}
								</td>
							</tr>
						';
					break;
					default:
						$div .= '
							<tr>
								<td>{$tables["fields"]["'.$key.'"]["name"]}</td>
								<td>{$info["'.$key.'"]}</td>
							</tr>
						';
				}
			} else {
				$div .= '
					<tr>
						<td>{$tables["fields"]["'.$key.'"]["name"]}</td>
						<td>{$info["'.$key.'"]}</td>
					</tr>
				';
			}
		}
		$html = '
			<table class="table">
				<thead>
					<tr>
						<th>字段</th>
						<th>值</th>  
					</tr>
				</thead>
				<tbody>
				'.$div.'
				<tr>
					<td colspan="2">
						{if checkurl($now_route["controller"]."/edit")}
						<a href="{:url("edit",array("id"=>$info["id"]))}" class="btn btn-primary" title="修改">
							<i class="fa fa-fw fa-lg fa-check-circle"></i>修改
						</a>
						{/if}
						{if checkurl($now_route["controller"]."/delete")}
						<a href="javascript:;" data-href="{:url("delete",array("id"=>$info["id"]))}" class="btn btn-secondary delete" title="删除">
							<i class="fa fa-fw fa-lg fa-times-circle"></i>删除
						</a>
						{/if}
					</td>
				</tr>
				</tbody>
			</table>
		';
		return $html;
	}

	/**
	 * 获取 create 模板代码
	 */
	protected function getcreate(){
		$hidden = array('id','update_time');
		$div = "";
		foreach($this->tables['fields'] as $key=>$value){
			if(!in_array($key,$hidden)){
				if(!empty($value['type'])) {
					switch($value['type']){
						case 'select':
							$div .= '
									<div class="form-group">
										<label class="control-label">{$tables["fields"]["'.$key.'"]["name"]}</label>
										<select class="form-control" placeholder="" name="'.$key.'">
											{foreach $tables["fields"]["'.$key.'"]["options"] as $key=>$vo } 
											<option value="{$key}">{$vo}</option>
											{/foreach}
										</select>
									</div>
							';
						break;

						case 'image':
							$div .= '<div class="form-group">
								<label class="control-label">{$tables["fields"]["'.$key.'"]["name"]}</label>
								<input class="form-control" type="text" placeholder="" name="'.$key.'" id="'.$key.'" value="" style="margin-bottom:10px;">
								<div class="form-group">
									<input id="'.$key.'file" type="file" multiple=true>
								</div>
							</div>
							<script>upload("'.$key.'file","'.$key.'");</script>
							';
						break;

						case 'time':
							$div .= '<div class="form-group">
								<label class="control-label">{$tables["fields"]["'.$key.'"]["name"]}</label>
								<div class="input-group date" id="'.$key.'" data-target-input="nearest">
									<input type="text" name="'.$key.'" class="form-control datetimepicker-input" data-target="#'.$key.'"/>
									<div class="input-group-append" data-target="#'.$key.'" data-toggle="datetimepicker">
										<div class="input-group-text"><i class="fa fa-calendar"></i></div>
									</div>
								</div>
								<script>
									$(function () {
										$("#'.$key.'").datetimepicker({
											locale: moment.locale("zh-cn"),
										});
									});
								</script>
							</div>
							';
						break;
						case 'ueditor':
							$div .= '<div class="form-group">
								<label class="control-label">{$tables["fields"]["'.$key.'"]["name"]}</label>
								<script id="'.$key.'" name="'.$key.'" type="text/plain" style="width:100%;height:300px;"></script>
								</div>
								<script>var '.$key.' = UE.getEditor("'.$key.'");</script>
								';
						break;
						case 'textarea':
							$div .= '
								<div class="form-group">
									<label class="control-label">{$tables["fields"]["'.$key.'"]["name"]}</label>
									<textarea class="form-control" rows="5" name="'.$key.'" ></textarea>
								</div>
							';
						break;
						default:
							$div .= '
								<div class="form-group">
									<label class="control-label">{$tables["fields"]["'.$key.'"]["name"]}</label>
									<input class="form-control" type="text" placeholder="" name="'.$key.'" value="">
								</div>
							';
						break;

					}
				}else{
					$div .= '
						<div class="form-group">
							<label class="control-label">{$tables["fields"]["'.$key.'"]["name"]}</label>
							<input class="form-control" type="text" placeholder="" name="'.$key.'" value="">
						</div>
					';
				}
			}
		}
		$html = '
			<form id="form">
				'.$div.'
				<div class="tile-footer">
					<button class="btn btn-primary" type="button" id="submitbutton">
						<i class="fa fa-fw fa-lg fa-check-circle"></i>提交
					</button>&nbsp;&nbsp;&nbsp;
				</div>
			</form>
		';
		return $html;
	}

	/**
	 * 获取 edit 模板代码
	 */
	protected function getedit(){
		$hidden = array('id','update_time');
		$div = "";
		foreach($this->tables['fields'] as $key=>$value){
			if(!in_array($key,$hidden)){
				if(!empty($value['type'])) {
					switch($value['type']){
						case 'select':
							$div .= '
								<div class="form-group">
									<label class="control-label">{$tables["fields"]["'.$key.'"]["name"]}</label>
									<select class="form-control" placeholder="" name="'.$key.'">
										{foreach $tables["fields"]["'.$key.'"]["options"] as $key=>$vo } 
										<option value="{$key}" {if $key==$info->getData("'.$key.'")}selected{/if}>{$vo}</option>
										{/foreach}
									</select>
								</div>
							';
						break;

						case 'image':
							$div .= '
								<div class="form-group">
									<label class="control-label">{$tables["fields"]["'.$key.'"]["name"]}</label>

									<div class="form-group">
									{if !empty($info["'.$key.'"])}
									<img src="{$info["'.$key.'"]}" style="max-width:100%;">
									{/if}
									</div>

									<input class="form-control" type="text" placeholder="" name="'.$key.'" value="{$info["'.$key.'"]}" id="'.$key.'" value="" style="margin-bottom:10px;">

									<div class="form-group">
									<input id="'.$key.'file" type="file" multiple=true>
									</div>
								</div>
								<script>upload("'.$key.'file","'.$key.'");</script>
							';
						break;

						case 'time':
							$div .='
								<div class="form-group">
									<label class="control-label">{$tables["fields"]["'.$key.'"]["name"]}</label>
									<div class="input-group date" id="'.$key.'" data-target-input="nearest">
										<input type="text" name="'.$key.'" class="form-control datetimepicker-input" data-target="#'.$key.'" value="{$info["'.$key.'"]}"/>
										<div class="input-group-append" data-target="#'.$key.'" data-toggle="datetimepicker">
											<div class="input-group-text"><i class="fa fa-calendar"></i></div>
										</div>
									</div>
								</div>
								<script>
									$(function () {
										$("#'.$key.'").datetimepicker({
											locale: moment.locale("zh-cn"),
										});
									});
								</script>
								';
						break;
						case 'ueditor':
							$div .= '<div class="form-group">
								<label class="control-label">{$tables["fields"]["'.$key.'"]["name"]}</label>
								<script id="'.$key.'" name="'.$key.'" type="text/plain" style="width:100%;height:300px;">{:htmlspecialchars_decode($info["'.$key.'"])}</script>
							</div>
							<script>var '.$key.' = UE.getEditor("'.$key.'");</script>
							';
						break;
						case 'textarea':
							$div .= '
								<div class="form-group">
									<label class="control-label">{$tables["fields"]["'.$key.'"]["name"]}</label>
									<textarea class="form-control" rows="5" name="'.$key.'" >{$info["'.$key.'"]}</textarea>
								</div>
							';
						break;
						default:
							$div .= '
								<div class="form-group">
									<label class="control-label">{$tables["fields"]["'.$key.'"]["name"]}</label>
									<input class="form-control" type="text" placeholder="" name="'.$key.'" value="{$info["'.$key.'"]}">
								</div>
							';
						break;
					}
				}else{
					$div .= '
						<div class="form-group">
							<label class="control-label">{$tables["fields"]["'.$key.'"]["name"]}</label>
							<input class="form-control" type="text" placeholder="" name="'.$key.'" value="{$info["'.$key.'"]}">
						</div>
					';
				}
			}
		}
		$html = '
			<form id="form">
				<input type="hidden" value="{$info.id}" name="id" />
				'.$div.'
				<div class="tile-footer">
					<button class="btn btn-primary" type="button" id="submitbutton">
						<i class="fa fa-fw fa-lg fa-check-circle"></i>提交
					</button>&nbsp;&nbsp;&nbsp;
					{if checkurl($now_route["controller"]."/delete")}
					<button type="button"  class="btn btn-secondary delete" data-href="{:url("delete",array("id"=>$info["id"]))}" >
						<i class="fa fa-fw fa-lg fa-times-circle"></i>删除
					</button>
					{/if}
				</div>
			</form>
		';
		return $html;
	}

	/**
	 * 获取 list 模板代码
	 */
	protected function getlist(){
		$field = "";
		foreach($this->tables['fields'] as $key=>$value){
			$field .= '
						<th>{$tables["fields"]["'.$key.'"]["name"]}</th>
					';
		}

		$div = "";
		foreach($this->tables['fields'] as $key=>$value){
			if(!empty($value['type'])) {
				switch($value['type']){
					case 'image':
						$div .= '
								<td><img src="{$vo["'.$key.'"]}" width="100"></td>
								';
					break;
					default:
						$div .= '
								<td>{$vo["'.$key.'"]}</td>
								';
				}
			} else {
				$div .= '
						<td>{$vo["'.$key.'"]}</td>
						';
			}

		}
		$count = count($this->tables['fields']);	
		$count += 2;

		$html = '
			<form id="delform">
			<table class="table">
				<thead>
					<tr>
						<th>
							<input type="checkbox" name="checkboxul" value="1" class="checkboxul">
						</th>
						'.$field.'
						<th>操作</th>
					</tr>
				</thead>
				<tbody>

				{foreach $lists as $key=>$vo } 
				<tr>
					<td>
						<input type="checkbox" name="id[]" value="{$vo.id}" class="checkboxli">
					</td>
					'.$div.'
					<td >
						{if checkurl($now_route["controller"]."/read")}
						<a href="{:url("read",array("id"=>$vo["id"]))}" title="浏览"><i class="fa fa-lg fa-fw fa-eye"></i></a>
						{/if}
						{if checkurl($now_route["controller"]."/edit")}
						<a href="{:url("edit",array("id"=>$vo["id"]))}" title="修改"><i class="fa fa-lg fa-fw fa-edit"></i></a>
						{/if}
						{if checkurl($now_route["controller"]."/delete")}
						<a href="javascript:;" data-href="{:url("delete",array("id"=>$vo["id"]))}" title="删除" class="delete">
							<i class="fa fa-lg fa-fw fa-trash-o"></i>
						</a>
						{/if}
						{if checkurl($now_route["controller"]."/copy")}
						<a href="javascript:;" title="复制活动" data-href="{:url("copy",array("id"=>$vo["id"]))}" class="copy">
							<i class="fa fa-lg fa-fw fa-copy"></i>
						</a>
						{/if}
					</td>
				</tr>
				{/foreach}
				<tr>
					<td colspan="'.$count.'">
						{if checkurl($now_route["controller"]."/delete")}
						<button class="btn btn-primary alldelete" type="button">
						删除
						</button>
						{/if}
					</td>
				</tr>

				</tbody>
			</table>
			</form>
		';
		return $html;
	}
}
